package com.phonetools.commonutils.android.hardware

import android.app.Activity
import android.content.ContentResolver
import android.content.pm.ActivityInfo.*
import android.database.ContentObserver
import android.hardware.SensorManager
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.provider.Settings.System.ACCELEROMETER_ROTATION
import android.view.OrientationEventListener

enum class RotationMode {
    ALL, SENSOR_PORTRAIT, SENSOR_LANDSCAPE,
    PORTRAIT, REVERSE_PORTRAIT,
    LANDSCAPE, REVERSE_LANDSCAPE
}

//观察屏幕旋转设置变化
class ScreenRotationObserver(
    val activity: Activity,
    handler: Handler = Handler(Looper.getMainLooper())
) : ContentObserver(handler) {
    private val contentResolver: ContentResolver = activity.contentResolver
    var enable: Boolean = true
    private var rotationMode: RotationMode = RotationMode.ALL

    fun setRotationMode(mode: RotationMode) {
        rotationMode = mode
        when (mode) {
            RotationMode.ALL -> {//任意方向，不需要设置
            }
            RotationMode.SENSOR_PORTRAIT, RotationMode.PORTRAIT -> {
                activity.requestedOrientation = SCREEN_ORIENTATION_PORTRAIT
            }
            RotationMode.SENSOR_LANDSCAPE, RotationMode.LANDSCAPE -> {
                activity.requestedOrientation = SCREEN_ORIENTATION_LANDSCAPE
            }
            RotationMode.REVERSE_PORTRAIT -> {
                activity.requestedOrientation = SCREEN_ORIENTATION_REVERSE_PORTRAIT
            }
            RotationMode.REVERSE_LANDSCAPE -> {
                activity.requestedOrientation = SCREEN_ORIENTATION_REVERSE_LANDSCAPE
            }
        }
    }

    //屏幕旋转设置改变时调用
    override fun onChange(selfChange: Boolean) {
        super.onChange(selfChange)
        getScreenOrientationSetting()
    }

    fun startObserver() {
        getScreenOrientationSetting()
        contentResolver.registerContentObserver(
            Settings.System
                .getUriFor(ACCELEROMETER_ROTATION), false, this
        )
    }

    fun stopObserver() {
        orientationEventListener.disable()
        contentResolver.unregisterContentObserver(this)
    }

    private fun getScreenOrientationSetting() {
        try {
            val screenChange =
                Settings.System.getInt(contentResolver, ACCELEROMETER_ROTATION)
            //是否开启自动旋转设置 1 开启 0 关闭
            if (screenChange == 1) {
                //Log.d(TAG, "开启旋转")
                if (orientationEventListener.canDetectOrientation()) {
                    //Log.d(TAG, "Can detect orientation")
                    orientationEventListener.enable()
                } else {
                    //Log.d(TAG, "Cannot detect orientation ")
                    orientationEventListener.disable()
                }
            } else {
                //Log.d(TAG, "关闭旋转")
                orientationEventListener.disable()
            }
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }
    }

    private val orientationEventListener = object : OrientationEventListener(
        activity.applicationContext,
        SensorManager.SENSOR_DELAY_NORMAL
    ) {
        override fun onOrientationChanged(i: Int) {
            //Log.d(TAG, "onOrientationChanged:$i")
            // i的范围是0～359
            if (i == ORIENTATION_UNKNOWN) {
                //Log.d(TAG, "ORIENTATION_UNKNOWN:$i")
                return
            }
            val screenOrientation = when (i) {
                in 0..45 -> SCREEN_ORIENTATION_PORTRAIT //垂直0
                in 45..135 -> SCREEN_ORIENTATION_REVERSE_LANDSCAPE //左转90=-270
                in 135..225 -> SCREEN_ORIENTATION_REVERSE_PORTRAIT //倒立180
                in 225..315 -> SCREEN_ORIENTATION_LANDSCAPE//右转90
                in 315..360 -> SCREEN_ORIENTATION_PORTRAIT //垂直0
                else -> SCREEN_ORIENTATION_PORTRAIT //垂直0
            }
            when (screenOrientation) {
                SCREEN_ORIENTATION_PORTRAIT -> {//SENSOR_PORTRAIT，PORTRAIT
                    if (rotationMode != RotationMode.SENSOR_PORTRAIT && rotationMode != RotationMode.PORTRAIT) return
                }
                SCREEN_ORIENTATION_REVERSE_PORTRAIT -> {//SENSOR_PORTRAIT，REVERSE_PORTRAIT
                    if (rotationMode != RotationMode.SENSOR_PORTRAIT && rotationMode != RotationMode.REVERSE_PORTRAIT) return
                }
                SCREEN_ORIENTATION_LANDSCAPE -> {//SENSOR_LANDSCAPE,LANDSCAPE
                    if (rotationMode != RotationMode.SENSOR_LANDSCAPE && rotationMode != RotationMode.LANDSCAPE) return
                }
                SCREEN_ORIENTATION_REVERSE_LANDSCAPE -> {//SENSOR_LANDSCAPE,REVERSE_LANDSCAPE
                    if (rotationMode != RotationMode.SENSOR_LANDSCAPE && rotationMode != RotationMode.REVERSE_LANDSCAPE) return
                }
            }
            if (enable && activity.requestedOrientation != screenOrientation) {
                //Log.d("RotationUtils", "旋转:$orientation")
                activity.requestedOrientation = screenOrientation
            }
        }
    }
}